<?php

class Mageex_Robot_Helper_Func extends Mage_Core_Helper_Abstract
{
	public function findImages($content)
	{
		preg_match_all('#<img(.*)src=\"(.*)\"(.*)>#smiU', $content, $matches);
		return $matches;
	}
	public function saveImage($url,$keyword)
	{
		$path 		= Mage::getBaseDir('media') . DS .'robot\images';
		$saveurl 	= Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'robot/images';
		
		
		if(strpos($url, "?") !== false) {return false;}

		$keyword = str_replace('"',"_",$keyword);	
		$keyword = urlencode($keyword);
		$keyword = str_replace("+","_",$keyword);
		$keyword = str_replace(" ","",$keyword);
		
		$contents = @file_get_contents($url);
		$filename = substr(md5(time()), 0, 5) . '_' . $keyword . "_" . basename($url);
		$filename = str_replace(" ","",$filename);
		$filename = str_replace("%20","",$filename);
		$filename = str_replace("%","",$filename);
		$filename = str_replace('*',"_",$filename);
		
		if(strpos($filename, ".") === false) {$filename .= ".jpg";}

		if(is_writable($path) && $contents) { 
			file_put_contents($path . '/' . $filename, $contents);
			return $saveurl . '/' . $filename;
		}

		return false;
	}
	public function getFieldMappingFromStr($strSerialized, $key)
	{
		$arrKey = explode('/', $key);
		
		$arrMap = unserialize($strSerialized);
		$arrField = array();
		foreach ( $arrKey as $field ) {	
			$arrField = is_array($arrMap["$field"]) ? $arrMap["$field"] : $arrField["$field"];
		}
		
		return $arrField;
	}
	public function getRandomKeyword($str, $kwExclude = '')
	{
		$arrKeyword = explode('<br />', nl2br($str));
		$key = array_rand($arrKeyword, 1);
		if ( $kwExclude != '' ) {
			$arrKeyword = $this->removeValueFromArr($kwExclude, $arrKeyword);
			$key = array_rand($arrKeyword, 1);
		}
		return $arrKeyword[$key];
	}
	public function removeValueFromArr($value, $arr)
	{
		$keyExclude = array_search($value, $arr);
		unset($arr[$keyExclude]);
		return $arr;
	}
}